package com.sihai.ehr.web.action.train;

import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.TrainCategory;
import com.sihai.ehr.model.biz.TrainClassroom;
import com.sihai.ehr.model.biz.TrainPlan;
import com.sihai.ehr.model.biz.TrainRealiaResource;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.service.TrainCategoryService;
import com.sihai.ehr.service.TrainPlanService;
import com.sihai.ehr.service.TrainRealiaResourceService;
import com.sihai.ehr.web.action.EHRAction;

/**
 * 培训类型控制器
 * 
 * @author henry
 * 
 */
@Results({
		@Result(name = "main", location = "train_main.jsp"),
		@Result(name = "realiaresource_manage", location = "realiaresource_manage.jsp"),
		@Result(name = "realiaresource_select_list", location = "realiaresource_select_list.jsp"),
		@Result(name = "realiaresource_apply", location = "realiaresource_apply.jsp"),
		@Result(name = "list", location = "realiaresource_list.jsp") })
public class TrainRealiaResourceAction extends EHRAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Log log = LogFactory.getLog(TrainRealiaResourceAction.class);

	@BeanInject
	private OrganizationService organizationService;
	@BeanInject
	private TrainRealiaResourceService trainRealiaResourceService;
	@BeanInject
	private TrainPlanService trainPlanService;

	private List<Organization> organizations;
	private LimitedList<TrainRealiaResource> resources;
	private TrainRealiaResource resource;
	private Long resourceId;
	private String ids;
	private Long planId;
	private String externRealiaDesc; // 额外教具

	@Action("/train/realiaresource_main")
	@Override
	public String execute() throws Exception {
		listTitle = "教具资源管理";
		listAction = "/train/realiaresource_list.xhtml";
		organizations = organizationService
				.findChildren(null, true, null, null);
		if (organizations != null && organizations.size() > 0) {
			if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
			organizationId = organizations.get(0).getId();
		}
		showChildOrg = false;
		return "main";
	}

	@Action("/train/realiaresource_list")
	public String list() {
		listAction = "/train/realiaresource_list.xhtml";
		resources = trainRealiaResourceService.getTrainRealiaResources(
				organizationId, createLimit(), createSorter());
		paging(resources);
		/* 设置翻页action */
		this.setPageUrl("train/realiaresource_list.xhtml");
		return "list";
	}

	@Action("/train/realiaresource_select_list")
	public String getRealiaResource() {
		listAction = "/train/realiaresource_select_list.xhtml";
		resources = trainRealiaResourceService.getTrainRealiaResources(
				organizationId, createLimit(), createSorter());
		paging(resources);
		// 设置翻页action
		this.setPageUrl("train/realiaresource_select_list.xhtml");
		return "realiaresource_select_list";
	}

	/**
	 * 教具资源处理意向
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/train/realiaresource_manage")
	public String dispatchRealiaResource() throws Exception {
		if (resourceId == null || resourceId <= 0) {
			// 添加
			resource = new TrainRealiaResource();
			resource.setOrganization(organizationService.get(organizationId));
		} else {
			// 修改
			resource = trainRealiaResourceService
					.getTrainRealiaResource(resourceId);
			if (resource.getOrganization().getTopOrganization() == null) {
				organizationId = resource.getOrganization().getId();
			} else {
				organizationId = resource.getOrganization()
						.getTopOrganization().getId();
			}
		}
		return "realiaresource_manage";
	}

	/**
	 * 提交教具处理
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/train/post_realiaresource")
	public String postRealiaResource() throws Exception {
		//
		if (resource == null) {
			if (log.isErrorEnabled()) {
				log.error("提交数据为空");
				return ERROR;
			}
		}
		if (resource.getId() == null) {
			// 添加
		} else {
			// 修改
		}
		// 保存数据
		try {
			trainRealiaResourceService.save(resource);
		} catch (Exception e) {
			log.equals(e.getMessage());
			return ERROR;
		}
		return "main";
	}

	/**
	 * 删除教具
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "/train/realiaresource_delete", results = { @Result(name = "success", type = "plainText") })
	public String deleteRealiaResource() throws Exception {
		if (StringUtils.isNotBlank(ids)) {
			try {
				trainRealiaResourceService.deleteTrainRealiaResource(ids);
			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error(e.getMessage());
				}
				return ERROR;
			}

		}

		return SUCCESS;
	}

	@Action("/train/realiaresource_apply")
	public String applyExternRealiaResource() {
		if (planId != null || planId > 0) {
			TrainPlan plan = trainPlanService.getTrainPlan(planId);
			externRealiaDesc = plan.getExternRealiaDesc();
		}
		return "realiaresource_apply";
	}

	/**
	 * 提交额外教具申请
	 * 
	 * @return
	 */
	@Action(value = "/train/post_externrealia_apply", results = { @Result(name = "success", type = "plainText") })
	public String postApplyExternRealiaResource() {
		if (externRealiaDesc == null || externRealiaDesc.isEmpty()) {
			if (log.isErrorEnabled()) {
				log.error("提交数据为空");
				return ERROR;
			}
		}
		// 保存数据
		try {
			TrainPlan plan = trainPlanService.getTrainPlan(planId);
			plan.setExternRealiaDesc(externRealiaDesc);
			trainPlanService.save(plan);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.getWriter().write("success");
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			log.equals(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}

	public void setOrganizations(List<Organization> organizations) {
		this.organizations = organizations;
	}

	public List<Organization> getOrganizations() {
		return organizations;
	}

	public LimitedList<TrainRealiaResource> getResources() {
		return resources;
	}

	public void setResources(LimitedList<TrainRealiaResource> resources) {
		this.resources = resources;
	}

	public TrainRealiaResource getResource() {
		return resource;
	}

	public void setResource(TrainRealiaResource resource) {
		this.resource = resource;
	}

	public Long getResourceId() {
		return resourceId;
	}

	public void setResourceId(Long resourceId) {
		this.resourceId = resourceId;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public Long getPlanId() {
		return planId;
	}

	public void setPlanId(Long planId) {
		this.planId = planId;
	}

	public String getExternRealiaDesc() {
		return externRealiaDesc;
	}

	public void setExternRealiaDesc(String externRealiaDesc) {
		this.externRealiaDesc = externRealiaDesc;
	}

}
